package com.xxx.springboot.distributedsession;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 分布式session attribute
 */
@Data
public class DistributedSessionAttribute implements Externalizable {

    private static final long serialVersionUID = -1504707278483164310L;
    
    private final Map<String, Serializable> attribute;

    public DistributedSessionAttribute() {
        this.attribute = new HashMap<>();
    }

    public void putAttribute(String name, Serializable value) {
        attribute.put(name, value);
    }

    public Serializable removeAttribute(String name) {
        return attribute.remove(name);
    }

    public Serializable getAttribute(String name) {
        return attribute.get(name);
    }

    public Set<String> getAttributeNames() {
        return attribute.keySet();
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        Set<String> keySet = attribute.keySet();
        String[] keys = keySet.toArray(new String[0]);
        Serializable[] values = new Serializable[keys.length];
        StringBuilder keyStr = new StringBuilder();
        for (int count = 0; count < keys.length; count++) {
            values[count] = attribute.get(keys[count]);
            keyStr.append(keys[count]).append("$$");
        }
        out.writeObject(keyStr.toString());
        out.writeObject(values);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        String keyStr = (String) in.readObject();
        if (StringUtils.isNotEmpty(keyStr)) {
            String[] keys = keyStr.split("\\$\\$");
            Serializable[] values = (Serializable[]) in.readObject();
            if (values != null && keys.length == values.length) {
                for (int count = 0; count < keys.length; count++) {
                    attribute.put(keys[count], values[count]);
                }
            }
        }
    }
}